# coding=utf-8
from appium import webdriver
import yaml
import os
from haoyunui.src.common import login_out
import   time
from Base.Base_Report import Report
import Base.BasePhoneMsg
import Base.test_case  as  case
import threading


def start_appium(port, bootstrap, udid):
    a = os.popen('netstat -ano | findstr "%s" ' % port)
    time.sleep(2)
    t1 = a.read()
    if "LISTENING" in t1:
        print("appium服务已经启动：%s" % t1)
    else:
        os.system("start /b appium -a 127.0.0.1 -p %s -bp %s -U %s" % (port, bootstrap, udid))


def stop_appium():  # 关闭所有的appium进程
    os.system("start /b taskkill /F /t /IM node.exe")


def get_desired_caps(devices_name):
    curpath = os.path.dirname(os.path.realpath(__file__))
    f = open( curpath+"\\script\\yaml_appium.yaml", "r", encoding="utf-8")
    a = f.read()
    f.close()
    # 把yaml文件转字典
    d = yaml.load(a)
    print(d)
    for ii in d:
        if devices_name in ii['desc']:  # 判断输入的设备名称是否存在
            ii['desired_caps']['app']=curpath+"\\script\\haoyun_4.4.0_100_201909092058.apk"
            devicesname = ii['desired_caps']['udid']
            print("devicesName: %s" % devicesname)
            start_appium(port=ii['port'], bootstrap=ii['bootstrap-port'], udid=ii['desired_caps']['udid'])
            return ii['desired_caps'], ii['port'],ii['desired_caps']['phone'],ii['desired_caps']['code']

def run_app(devices_name):

    # 配置参数
    desired_caps = get_desired_caps(devices_name)
    print(desired_caps)
    # print(desired_caps[1])
    # 执行代码
    print('http://127.0.0.1:%s/wd/hub' % desired_caps[1], desired_caps[0])
    driver = webdriver.Remote('http://127.0.0.1:%s/wd/hub' % desired_caps[1], desired_caps[0])
    #登录
    login_out.login_out(driver,desired_caps[2],desired_caps[3])
    #执行monkey
    case.ram_monkey(devices_name)
    #生成报告
    Report.report(devices_name)
    #关闭应用
    driver.close_app()
    #卸载    --卸载需要root权限
    # driver.RemoveApp(Config.package_name);
    time.sleep(5)


class MonkeyThread(threading.Thread):
    def __init__(self, dev):
        threading.Thread.__init__(self)
        self.thread_stop = False
        self.dev = dev
    def run(self):
      run_app(self.dev)


def create_threads_monkey(device_list):
    thread_instances = []
    if device_list != []:
        for id_device in device_list:
            dev = id_device
            instance = MonkeyThread(dev)
            thread_instances.append(instance)
        for instance in thread_instances:
            instance.start()
        stop_appium()

if  __name__=="__main__":
  clean_report=""
  device_list = Base.BasePhoneMsg.get_devices()
  if device_list!=[]:
    create_threads_monkey(device_list)
  else:
    print("设备不存在")